﻿using Oracle.ManagedDataAccess.Client;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.Web.Script.Serialization;

namespace SynService
{
    public partial class MyService : ServiceBase
    {
        public MyService()
        {
            InitializeComponent();
        }
        //定时器
        private static System.Timers.Timer timer;
        //获取Appconfig配置同步时间
        private static string SynTimer = ConfigurationManager.AppSettings["SynTimer"];
        protected override void OnStart(string[] args)
        {
            CYQ.Data.Log.WriteLogToTxt($"{DateTime.Now},服务启动！");

            timer = new System.Timers.Timer(1000 * 60 * 60 * Convert.ToInt32(SynTimer));//1000 seconds 1秒
            //timer = new System.Timers.Timer(1000 * 10);//1000 seconds 1秒
            timer.Enabled = true;
            timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
            timer.AutoReset = true;
            timer.Start();
        }

        private static string OracleStr = ConfigurationManager.ConnectionStrings["local_Orcl"].ConnectionString;//获取Appconfig配置Oracle数据库连接
        private static string ConfigCity = ConfigurationManager.AppSettings["City"];//获取Appconfig配置天气服务城市
        OracleConnection conn;

        #region 定时器执行任务

        /// <summary>
        /// 定时器中定时执行的任务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        public void OnTimer(object sender, ElapsedEventArgs args)
        {
            //检查同步开始，暂时停用定时服务，完成后再开启
            timer.Enabled = false;
            timer.Interval = 1000 * 60 * 60 * Convert.ToInt32(SynTimer);
            //timer.Interval = 1000 * 10;
            try
            {
                string Resource = HttpGet("http://wthrcdn.etouch.cn/weather_mini?city=" + ConfigCity);
                JavaScriptSerializer js = new JavaScriptSerializer();
                ResEntity entity = js.Deserialize<ResEntity>(Resource);
                if (entity != null)
                {
                    if (entity.status == 1000)
                    {
                        string Infodate = DateTime.Now.ToString("yyyy-MM-dd");//日期
                        string[] weekdays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
                        string week = weekdays[Convert.ToInt32(DateTime.Now.DayOfWeek)];//星期

                        string MaxWd = entity.data.forecast[0].high.Substring(3);
                        string MinWd = entity.data.forecast[0].low.Substring(3);
                        string FL = (entity.data.forecast[0].fengxiang) + (entity.data.forecast[0].fengli).Substring(9, 2);
                        string Type = entity.data.forecast[0].type;

                        #region Oracle数据库插入

                        //Oracle数据库操作
                        conn = new OracleConnection(OracleStr);
                        //打开连接
                        conn.Open();
                        //定义操作：查询
                        string sql = "select * from TianQi where Fildate>=to_date('" + Infodate + "','yyyy-mm-dd')";
                        OracleCommand cmd = conn.CreateCommand();
                        cmd.CommandText = sql;
                        cmd.CommandType = System.Data.CommandType.Text;
                        OracleDataAdapter adapter = new OracleDataAdapter(cmd);
                        DataSet dataSet = new DataSet();
                        adapter.Fill(dataSet);
                        adapter.Dispose();
                        if (dataSet.Tables[0].Rows.Count > 0)
                        {
                            //定义操作：更新
                            sql = "update TianQi set HighTemp='" + MaxWd + "',LowTemp='" + MinWd + "',TypeInfo='" + Type + "',FL='" + FL + "' where Fildate=to_date('" + Infodate + "','yyyy-mm-dd')";
                        }
                        else
                        {
                            //定义操作：新增
                            sql = "Insert Into TianQi Values(to_date('" + Infodate + "','yyyy-mm-dd'),'" + week + "','" + MaxWd + "','" + MinWd + "','" + Type + "','" + FL + "')";
                        }

                        cmd.CommandText = sql;
                        cmd.CommandType = CommandType.Text;

                        //执行并设置返回值
                        int reader = cmd.ExecuteNonQuery();

                        conn.Close();

                        #endregion
                    }
                }
            }
            catch (Exception e)
            {
                CYQ.Data.Log.WriteLogToTxt($"{DateTime.Now},错误日志：" + e.Message);
            }
            timer.Enabled = true;

        }

        /// <summary>
        /// POST 接口请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public string HttpPost(string url, string body)
        {
            //把用户传过来的数据转成“UTF-8”的字节流
            Encoding encoding = Encoding.UTF8;
            //先根据用户请求的uri构造请求地址
            //创建Web访问对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            // request.Accept = "application/json";
            request.ContentType = "application/json; charset=UTF-8";
            request.Headers["Accept-Encoding"] = "gzip, deflate";
            request.AutomaticDecompression = DecompressionMethods.GZip;

            //HttpCookie Cookie = System.Web.HttpContext.Current.Request.Cookies["admin"];  //若是需要登录过后再能访问获取url的数据，需要在请求头中设置cookie值
            //if (Cookie != null)
            //request.Headers.Add("Cookie", Cookie.Value.ToString());

            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            //通过Web访问对象获取响应内容
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //通过响应内容流创建StreamReader对象，因为StreamReader更高级更快
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();//利用StreamReader就可以从响应内容从头读到尾
            }
        }

        /// <summary>
        /// GET接口请求
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public string HttpGet(string url)
        {
            var client = new RestClient(url);
            client.Timeout = -1;
            var request = new RestRequest(Method.GET);
            IRestResponse response = client.Execute(request);
            return response.Content;
        }

        #region 接口返回参数实体类

        public class ResEntity
        {
            public data data { get; set; }
            public int status { get; set; }
            public string desc { get; set; }

        }
        public class data
        {
            public yesterday yesterday { get; set; }
            public string city { get; set; }
            public List<forecast> forecast { get; set; }
            public string ganmao { get; set; }
            public string wendu { get; set; }
        }
        public class yesterday
        {
            public string date { get; set; }
            public string high { get; set; }
            public string fx { get; set; }
            public string low { get; set; }
            public string fl { get; set; }
            public string type { get; set; }
        }
        public class forecast
        {
            public string date { get; set; }
            public string high { get; set; }
            public string fengli { get; set; }
            public string low { get; set; }
            public string fengxiang { get; set; }
            public string type { get; set; }
        }


        #endregion


        #endregion

        protected override void OnStop()
        {
            CYQ.Data.Log.WriteLogToTxt($"{DateTime.Now},服务停止！");
        }
    }
}
